package com.baosight.risk.common;

import com.baosight.iplat4j.core.data.ibatis.dao.Dao;
import com.baosight.iplat4j.core.ioc.spring.PlatApplicationContext;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.context.ApplicationContext;

/**
 * 操作Spring Context工具类，实现为singleton
 *
 * @author
 */
@SuppressWarnings("rawtypes")
public final class BeanContext {
    private static final String FIELD_NAME_DAO = "dao";
    private static ApplicationContext instance;
    private static String realPath;

    private BeanContext() {

    }

    /**
     * 判断是否注册了指定名称的Bean;
     *
     * @param beanName
     * @return
     */
    public static boolean hasBean(String beanName) {
        if (instance == null) {
            initContext();

        }
        return instance.containsBean(beanName);
    }

    /**
     * 从SpringContext中取得对象
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        if (instance == null) {
            initContext();

        }
        return instance.getBean(beanName);
    }

    /**
     * 根据类的类型创建实例，如果类有setDao()方法，则设置默认的DAO类实例
     *
     * @param clazz
     * @return
     */
    public static Object getObject(Class clazz) {
        try {
            Object obj = clazz.newInstance();

            if (PropertyUtils.isWriteable(obj, FIELD_NAME_DAO)) {
                PropertyUtils.setProperty(obj, FIELD_NAME_DAO, getDao());
            }

            return obj;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    private static synchronized void initContext() {
        instance = PlatApplicationContext.getApplicationContext();
    }

    /**
     * 取得DAO对象实例
     *
     * @return
     */
    public static Dao getDao() {
        Dao dao = (Dao) getBean(FIELD_NAME_DAO);
        return dao;
    }


    public static String getRealPath() {
        return realPath;
    }

    public static void setRealPath(String realPath1) {
        realPath = realPath1;
    }
}
